package itdep.jsf.internal;

import ga.domain.Entity;
import ga.domain.repository.EntityRepository;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import java.io.Serializable;

/**
 * @author Ivan Khalopik
 * @version $Revision: 21 $ $Date: 2010-06-19 06:52:13 +0000 (Sat, 19 Jun 2010) $
 */
public class EntityConverter<PK extends Serializable> implements Converter, Serializable {
	private final EntityRepository repository;
	private final Class<PK> pkClass;

	public EntityConverter(EntityRepository repository, Class<PK> pkClass) {
		this.repository = repository;
		this.pkClass = pkClass;
	}

	@SuppressWarnings({"unchecked"})
	public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException {
		final PK pk = (PK) getPkConverter(context).getAsObject(context, component, value);
		return pk != null ? repository.get(getEntityClass(context, component), pk) : null;
	}

	@SuppressWarnings({"unchecked"})
	public String getAsString(final FacesContext context, final UIComponent component, final Object value) throws ConverterException {
		final Entity<PK> entity = (Entity<PK>) value;
		return entity != null ? getPkConverter(context).getAsString(context, component, entity.getId()) : null;
	}

	private Class getEntityClass(FacesContext facesContext, UIComponent component) {
		return component.getValueExpression("value").getType(facesContext.getELContext());
	}

	private Converter getPkConverter(FacesContext context) {
		return context.getApplication().createConverter(pkClass);
	}
}
